/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
    let ans = [];
    nums.sort((a, b) => a - b) //排序
    let n = nums.length
    for (let i = 0; i < n - 2; i++) {
        let x = nums[i]
        if (i > 0 && nums[i] === nums[i - 1]) { //如果遍历的数和上一个数相等，会出现相同的结果元组，跳过
            continue
        }
        let left = i + 1
        let right = n - 1
        while (left < right) {
            let sum = nums[left] + nums[right] + x
            if (sum === 0) { //这里left和right也可能有重复
                ans.push([x, nums[left], nums[right]])
                left++ //跳过重复值
                while (left < right && nums[left] === nums[left - 1]) {
                    left++
                }
                right--
                while (left < right && nums[right] === nums[right + 1]) {
                    right--
                }
            } else if (sum < 0) {
                left++
            } else {
                right--
            }
        }
    }
    return ans;
};

let nums = [-1, 0, 1, 2, -1, -4]
console.log(threeSum(numbers));